﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Jermaine.UI.Extensions
{
    public static class DataGridViewExtensions
    {
        /// <summary>
        /// 选取当前行
        /// </summary>
        /// <param name="dgv"></param>
        /// <param name="rowIndex"></param>
        public static void SelectRow(this DataGridView dgv, int rowIndex) {
            if (rowIndex < 0 || rowIndex > dgv.RowCount - 1) {
                return;
            }
            dgv.Rows[rowIndex].Selected = true;
            dgv.CurrentCell = dgv.Rows[rowIndex].Cells[0];

        }

        /// <summary>
        /// 获取当前表格绑定的数据源
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dgv"></param>
        /// <returns></returns>
        public static T GetDataSource<T>(this DataGridView dgv) {
            if (dgv.DataSource == null) {
                return default(T);
            } else {
                return (T)dgv.DataSource;
            }

        }

        /// <summary>
        /// 获取当前行绑定的实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dgv"></param>
        /// <returns></returns>
        public static T GetCurrentRowItem<T>(this DataGridView dgv) {
            if (dgv.DataSource == null) {
                return default(T);
            }
            if (dgv.RowCount == 0) {
                return default(T);
            }

            var index = dgv.CurrentRow.Index;
            if (index > dgv.RowCount - 1 || index < 0) {
                return default(T);
            }

            var item = dgv.Rows[index].DataBoundItem;
            if (item == null) {
                return default(T);
            }
            return (T)item;
        }
    }
}
